//
//  HJSelectFridendsSearchController.m
//  KaiChat
//
//  Created by lx on 2023/11/3.
//

#import "HJSelectFridendsSearchController.h"
#import "QMUITextField.h"
#import "TJEmptyDataHandler.h"
#import "HJSelectMemberView.h"
#import "HJSelectFridendCell.h"
#import "HJIM.h"

@interface HJSelectFridendsSearchController ()<QMUITextFieldDelegate>

@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;
@property (nonatomic, weak) QMUITextField *textField;
@property (nonatomic, weak) HJSelectMemberView *selectMemberView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, assign) NSInteger lastCount;
@property (nonatomic, strong) NSMutableArray *searchDatas;
@property (nonatomic, assign) NSInteger lastSearchCount;

@end

@implementation HJSelectFridendsSearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.lastSearchCount = 0;
    self.navigationBar.lineView.hidden = YES;
    
    UIView *searchView = [UIView addToView:self.navigationBar.contentView];
    searchView.backgroundColor = UIColor.tj_F6F6F6Color;
    searchView.addCornerRadius(10);
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.left.offset(60);
        make.centerY.offset(0);
        make.height.offset(40);
    }];
    
    UIImageView *searchIcon = [UIImageView addToView:searchView];
    searchIcon.image = [UIImage imageNamed:@"search_icon"];
    [searchIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(15);
        make.width.height.offset(20);
    }];
    
    QMUITextField *textField = [QMUITextField addToView:searchView];
    textField.placeholder = @"Enter user UID to search";
    textField.maximumTextLength = 20;
    textField.font = UIFontMake(14);
    textField.returnKeyType = UIReturnKeyDone;
    textField.delegate = self;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.equalTo(searchIcon.mas_right).offset(10);
        make.right.offset(0);
        make.height.offset(40);
    }];
    
    _emptyDataHandler =  [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView configuration:^TJEmptyDataType(TJEmptyDataModel * _Nonnull dataModel) {
        dataModel.iconName = @"search_empty";
        dataModel.text = @"results not found";
        return TJEmptyDataTypeBase;
    }];
    _textField = textField;
    
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 90)];
    headerView.backgroundColor = UIColor.whiteColor;
    
    TJWeakify(self)
    HJSelectMemberView *selectMemberView = [HJSelectMemberView addToView:headerView];
    [selectMemberView setDidClickDeleteButtonBlock:^(HJChatFriendModel * _Nonnull model) {
        [weakself didSelectRowWithModel:model];
    }];
    [selectMemberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(0);
        make.top.offset(10);
    }];
    
    _headerView = headerView;
    _selectMemberView = selectMemberView;
    
    self.view.backgroundColor = UIColor.whiteColor;
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    self.tableView.tableHeaderView = headerView;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView registerClass:HJSelectFridendCell.class forCellReuseIdentifier:@"HJSelectFridendCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 64;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.bottom.offset(0);
    }];
    
    [self updateSelectMemberViewHeight];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    
    NSString *keyword = textField.text;
    UITextRange *textRange = textField.markedTextRange;
    if (textRange) return;
    
    [self.searchDatas removeAllObjects];

    if (isEmptyString(keyword)) {
        self.emptyDataHandler.displayEmpty = NO;
        [self.tableView reloadData];
        return;
    }
    
    for (HJChatFriendModel *obj in self.datas) {
        NSRange range = [obj.nickname rangeOfString:keyword options:NSCaseInsensitiveSearch];
        if (range.location != NSNotFound) {
             [self.searchDatas addObject:obj];
        }
    }
    
    if (self.searchDatas.count == 0 && self.lastSearchCount == 0) return;

    self.emptyDataHandler.displayEmpty = YES;
    [self.tableView reloadData];
    self.lastSearchCount = self.searchDatas.count;
}

- (void)updateSelectState:(HJChatFriendModel *)obj {
    if (self.selectDatas.count == 0) return;
    
    for (HJChatFriendModel *model in self.selectDatas) {
        if ([obj.userId isEqualToString:model.userId]) {
            obj.isSelect = model.isSelect;
            break;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchDatas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJSelectFridendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJSelectFridendCell" forIndexPath:indexPath];
    HJChatFriendModel *model = self.searchDatas[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HJChatFriendModel *model = self.searchDatas[indexPath.row]; 
    [self didSelectRowWithModel:model];
}

- (void)didSelectRowWithModel:(HJChatFriendModel *)model {
    
    model.isSelect = !model.isSelect;
    
    HJSelectFridendCell *cell = [self getVisibleCellWithModel:model];
    cell.model = model;
    if (model.isSelect) {
        if (![self.selectDatas containsObject:model]) {
            [self.selectDatas addObject:model];
        }
    } else {
        if ([self.selectDatas containsObject:model]) {
            [self.selectDatas removeObject:model];
        }
    }
    
    [self updateSelectMemberViewHeight];
}


- (nullable HJSelectFridendCell *)getVisibleCellWithModel:(HJChatFriendModel *)model {
    for (HJSelectFridendCell *cell in self.tableView.visibleCells) {
        if (cell.model == model) {
            return cell;
        }
    }
    return nil;
}


- (void)updateSelectMemberViewHeight {
    if (_lastCount > 0 && self.selectDatas.count > 0) {
        self.lastCount = self.selectDatas.count;
        self.selectMemberView.datas = self.selectDatas;
        return;
    };
    
    [UIView animateWithDuration:0.01 animations:^{
        if (self.selectDatas.count > 0) {
            self.headerView.tj_height = 90;
            self.tableView.tableHeaderView = self.headerView;
            [self.selectMemberView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.offset(0);
                make.height.offset(90);
                make.top.offset(0);
            }];
        } else {
            self.headerView.tj_height = 0;
            self.tableView.tableHeaderView = self.headerView;
            [self.selectMemberView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.offset(0);
                make.height.offset(0);
                make.top.offset(KNavBarHight);
            }];;
        }
    } completion:^(BOOL finished) {
        self.lastCount = self.selectDatas.count;
        self.selectMemberView.datas = self.selectDatas;
    }];
}

- (void)popViewController {
    [super popViewController];
    
    if (_selectComplete) {
        _selectComplete();
    }
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}

- (NSMutableArray *)searchDatas {
    if (!_searchDatas) {
        _searchDatas = [NSMutableArray array];
    }
    return _searchDatas;
}

@end
